package com.example.ribbonserver.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2020/4/22
 */
public class HelloGetCommand extends HystrixCommand<String> {

    private static final Logger logger = LoggerFactory.getLogger(HelloGetCommand.class);

    private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("CommandKey");

    private RestTemplate restTemplate;

    private String name;

    public HelloGetCommand(RestTemplate restTemplate, String name) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GetSetGet")).andCommandKey(GETTER_KEY));
        this.restTemplate = restTemplate;
        this.name = name;
    }

    @Override
    protected String run() throws Exception {
        logger.info("HelloGetCommand:run:name = {}", name);
        return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name=" + name, String.class);
    }

    @Override
    protected String getCacheKey() {
        logger.info("HelloGetCommand:getCacheKey:name = {}", name);
        //将name放入缓存
        return String.valueOf(name);
    }

    public static void flushCache (String name) {
        //清除缓存
        HystrixRequestCache
                .getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance())
                .clear(String.valueOf(name));
    }

    @Override
    protected String getFallback() {
        logger.info("HelloGetCommand:getFallback:name = {}", name);
        return "Hystrix ....";
    }
}
